package response

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// 统一响应结构
type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 成功响应
func SuccessResponse(data interface{}) Response {
	return Response{
		Code: 0,
		Msg:  "success",
		Data: data,
	}
}

// 错误响应
func ErrorResponse(code int, msg string) Response {
	return Response{
		Code: code,
		Msg:  msg,
		Data: nil,
	}
}

// 定义上下文键
const (
	ResponseFuncKey = "ResponseFuncKey"
)

// Success 成功响应函数
func Success(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, SuccessResponse(data))
}

// Error 错误响应函数
func Error(c *gin.Context, code int, msg string) {
	c.JSON(http.StatusOK, ErrorResponse(code, msg))
}

// ResponseMiddleware 统一响应中间件
func ResponseMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 将响应函数绑定到上下文
		c.Set(ResponseFuncKey, gin.H{
			"Success": func(data interface{}) {
				Success(c, data)
			},
			"Error": func(code int, msg string) {
				Error(c, code, msg)
			},
		})

		// 处理请求
		c.Next()
	}
}

// GetResponseFuncs 获取响应函数
func GetResponseFuncs(c *gin.Context) (success func(interface{}), err func(int, string)) {
	val, exists := c.Get(ResponseFuncKey)
	if !exists {
		return func(data interface{}) {
				c.JSON(http.StatusOK, SuccessResponse(data))
			}, func(code int, msg string) {
				c.JSON(http.StatusOK, ErrorResponse(code, msg))
			}
	}

	funcs := val.(gin.H)
	return funcs["Success"].(func(interface{})), funcs["Error"].(func(int, string))
}
